package com.tql.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tql.mall.model.customer.Customer;
import com.tql.mall.model.customer.CustomerRegisterVo;
import com.tql.mall.model.enums.customer.CustRegiFailEnum;
import com.tql.mall.user.mapper.CustomerMapper;
import com.tql.mall.user.service.CustomerService;
import com.tql.mall.user.utils.VertifyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public String register(CustomerRegisterVo customerRegisterVo) {
        //信息是否完整
        if (!VertifyUtil.isInfoComplete(customerRegisterVo)){
            return CustRegiFailEnum.FAIL_INFO_INCOMPLET.getMsg();
        }
        //两次输入的密码是否一致
        if (!customerRegisterVo.getPasswd().equals(customerRegisterVo.getSurePasswd())){
            return CustRegiFailEnum.FAIL_PASSWD_DIFFERNET.getMsg();
        }
        //手机号是否已经绑定
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",customerRegisterVo.getPhone());
        Customer customer = baseMapper.selectOne(queryWrapper);
        if (customer != null) return CustRegiFailEnum.FAIL_PHONE_USED.getMsg();
        //账号是否重复
        QueryWrapper<Customer> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("account",customerRegisterVo.getAccount());
        Customer customer1 = baseMapper.selectOne(queryWrapper1);
        if (customer1 != null) return CustRegiFailEnum.FAIL_ACCOUNT_REPEATED.getMsg();
        //验证码是否正确
        String codeCached = redisTemplate.opsForValue().get(customerRegisterVo.getPhone());
        if (StringUtils.isEmpty(codeCached) || !customerRegisterVo.getCode().equals(codeCached) ){
            return CustRegiFailEnum.FAIL_CODE_ERROR.getMsg();
        }
        //执行添加
        Customer customer2 = new Customer();
        BeanUtils.copyProperties(customerRegisterVo,customer2);
        customer2.setPasswd(DigestUtils.md5DigestAsHex(customerRegisterVo.getPasswd().getBytes()));
        baseMapper.insert(customer2);
        return null;
    }
}